package backend

import (
	"github.com/gin-gonic/gin"
	"naio/constant"
	"naio/errs"
	"naio/model"
	"naio/serializer"
	"naio/validate"
	"net/http"
	"strconv"
)

//OK
func (h *Handler) CategoryBrowse(c *gin.Context) {
	var _pid = c.DefaultQuery("pid", "0")
	var _page = c.DefaultQuery("page", "1")
	var _size = c.DefaultQuery("size", "15")

	pid, _ := strconv.Atoi(_pid)
	page, _ := strconv.Atoi(_page)
	size, _ := strconv.Atoi(_size)

	var cateVOList []constant.BackendCategoryResponse
	cateList, total := h.service.CategoryService.GetCategoryList(pid, page, size)
	for _, v := range *cateList {
		cateVO := constant.BackendCategoryResponse{}
		cateVO.Id = v.Id
		cateVO.ParentId = v.ParentId
		cateVO.Name = v.Name
		cateVO.Sort = v.Sort
		cateVO.Online = v.Online
		cateVO.Picture = v.Picture
		cateVO.Description = v.Description
		cateVOList = append(cateVOList, cateVO)
	}

	data := make(map[string]interface{})
	data["list"] = cateVOList
	data["total"] = total
	res := serializer.SuccessMessage{Code: 0, Msg: "ok", Data: nil}
	res.Data = data
	res.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
	c.JSON(http.StatusOK, res)

}

func (h *Handler) CategoryFetch(c *gin.Context) {
	var _id = c.Param("id")
	if _id == "" {
		panic(errs.NewMyAPIError(errs.ErrorParameterValidate, "id参数必填!!!"))
	}

	id, _ := strconv.Atoi(_id)
	category := h.service.CategoryService.GetCategoryById(id)
	res := serializer.SuccessMessage{Code: 0, Msg: "ok", Data: nil}
	res.Data = category
	res.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
	c.JSON(http.StatusOK, res)
}

func (h *Handler) CategoryUpdate(c *gin.Context) {
	req := constant.BackendCategoryRequest{}
	if err := c.ShouldBindJSON(&req); err != nil {
		panic(errs.NewMyAPIError(errs.InvalidParams, err.Error()))
	}

	validator, _ := validate.Default()
	if check := validator.CheckStruct(req); !check {
		panic(errs.NewMyAPIError(errs.InvalidParams, validator.GetAllErrorString()))
	}

	if req.Id == 0 {
		// add
		category := h.service.CategoryService.GetCategoryByName(req.Name)
		if category != nil {
			panic(errs.NewMyAPIError(errs.ErrorCategoryExist, "分类已存在"))
		}
		if req.ParentId != 0 {
			_ = h.service.CategoryService.GetCategoryById(req.ParentId)
		}
		// 此分类不存在并且父级分类存在
		category = &model.CategoryModel{
			ParentId:    req.ParentId, // pid==0或者父级分类存在
			Name:        req.Name,
			Sort:        req.Sort,
			Online:      req.Online,
			Picture:     req.Picture,
			Description: req.Description,
		}
		h.service.CategoryService.AddCategory(category)
	} else{
		// update
		category := h.service.CategoryService.GetCategoryByName(req.Name)
		if category != nil && category.Id != req.Id {
			panic(errs.NewMyAPIError(errs.ErrorCategoryExist, "分类已经存在"))
		}

		category = h.service.CategoryService.GetCategoryById(req.Id)
		if category == nil || category.Del == 1 {
			panic(errs.NewMyAPIError(errs.ErrorCategoryNotExist, "分类异常"))
		}

		category = &model.CategoryModel{
			Id:          req.Id,
			ParentId:    req.ParentId, // pid==0或者父级分类存在
			Name:        req.Name,
			Sort:        req.Sort,
			Online:      req.Online,
			Picture:     req.Picture,
			Description: req.Description,
		}
		h.service.CategoryService.UpdateCategory(category)
	}

	res := serializer.SuccessMessage{Code: 0, Msg: "ok", Data: nil}
	res.RequestUrl = c.Request.Method + " " + c.Request.URL.String()
	c.JSON(http.StatusOK, res)
}

func (h *Handler) CategoryDelete(c *gin.Context) {
	var _id = c.Param("id")
	if _id == "" {
		panic(errs.NewMyAPIError(errs.ErrorParameterValidate, "id参数必填!!!"))
	}

	id, _ := strconv.Atoi(_id)
	category := h.service.CategoryService.GetCategoryById(id)
	if category == nil {
		panic(errs.NewMyAPIError(errs.ErrorCategoryNotExist, "分类不存在"))
	}

	category.Del = constant.DELETE
	h.service.CategoryService.UpdateCategory(category)
}